import { invoke } from '@tauri-apps/api/core';

export interface VideoInfo {
  file_path: string;
  file_size: number;
  duration?: string;
  bitrate?: string;
  resolution?: string;
  codec?: string;
  fps?: string;
}

export interface ProcessParams {
  format: string;
  quality?: number;
  bitrate?: number;
  resolution?: [number, number];
}

export interface ExtractParams {
  audio_format: string;
  bitrate?: number;
  sample_rate?: number;
}

export interface ProcessResult {
  task_id: string;
  status: ProcessStatus;
  progress: number;
  output_path?: string;
  error_message?: string;
  start_time: string;
  end_time?: string;
}

export enum ProcessStatus {
  Pending = 'Pending',
  Processing = 'Processing',
  Completed = 'Completed',
  Failed = 'Failed',
  Cancelled = 'Cancelled',
}

export interface BatchTask {
  task_id: string;
  input_path: string;
  output_path: string;
  params: ProcessParams;
  status: ProcessStatus;
  progress: number;
}

export interface BatchResult {
  batch_id: string;
  total_tasks: number;
  completed_tasks: number;
  failed_tasks: number;
  results: ProcessResult[];
}

export interface VideoFormat {
  name: string;
  extension: string;
  supported_codecs: string[];
}

export interface AudioFormat {
  name: string;
  extension: string;
  supported_bitrates: number[];
}

export class VideoService {
  static async convertVideo(
    inputPath: string,
    outputPath: string,
    params: ProcessParams
  ): Promise<ProcessResult> {
    try {
      const result = await invoke('convert_video', {
        request: {
          input_path: inputPath,
          output_path: outputPath,
          format: params.format,
          quality: params.quality,
          bitrate: params.bitrate,
          resolution: params.resolution,
        },
      });

      return result as ProcessResult;
    } catch (error) {
      throw new Error(`视频转换失败: ${error}`);
    }
  }

  static async extractAudio(
    videoPath: string,
    audioPath: string,
    params: ExtractParams
  ): Promise<ProcessResult> {
    try {
      const result = await invoke('extract_audio', {
        request: {
          video_path: videoPath,
          audio_path: audioPath,
          audio_format: params.audio_format,
          bitrate: params.bitrate,
          sample_rate: params.sample_rate,
        },
      });

      return result as ProcessResult;
    } catch (error) {
      throw new Error(`音频提取失败: ${error}`);
    }
  }

  static async getVideoInfo(filePath: string): Promise<VideoInfo> {
    try {
      const result = await invoke('get_video_info', {
        filePath,
      });

      return result as VideoInfo;
    } catch (error) {
      throw new Error(`获取视频信息失败: ${error}`);
    }
  }

  static async batchProcess(tasks: BatchTask[]): Promise<BatchResult> {
    try {
      const result = await invoke('batch_process_videos', {
        tasks,
      });

      return result as BatchResult;
    } catch (error) {
      throw new Error(`批量处理失败: ${error}`);
    }
  }

  static async getSupportedVideoFormats(): Promise<VideoFormat[]> {
    try {
      const result = await invoke('get_supported_video_formats');
      return result as VideoFormat[];
    } catch (error) {
      throw new Error(`获取支持的视频格式失败: ${error}`);
    }
  }

  static async getSupportedAudioFormats(): Promise<AudioFormat[]> {
    try {
      const result = await invoke('get_supported_audio_formats');
      return result as AudioFormat[];
    } catch (error) {
      throw new Error(`获取支持的音频格式失败: ${error}`);
    }
  }

  static async getActiveTasks(): Promise<Record<string, ProcessStatus>> {
    try {
      const result = await invoke('get_active_tasks');
      return result as Record<string, ProcessStatus>;
    } catch (error) {
      throw new Error(`获取活动任务失败: ${error}`);
    }
  }

  static async cancelTask(taskId: string): Promise<boolean> {
    try {
      const result = await invoke('cancel_task', {
        taskId,
      });

      return result as boolean;
    } catch (error) {
      throw new Error(`取消任务失败: ${error}`);
    }
  }

  // 工具方法：创建默认处理参数
  static createDefaultParams(format: string): ProcessParams {
    const defaultParams: Record<string, ProcessParams> = {
      mp4: { format: 'mp4', quality: 23, bitrate: 2000 },
      avi: { format: 'avi', quality: 20, bitrate: 1500 },
      mov: { format: 'mov', quality: 23, bitrate: 2000 },
      mkv: { format: 'mkv', quality: 23, bitrate: 2000 },
      wmv: { format: 'wmv', quality: 20, bitrate: 1500 },
    };

    return defaultParams[format] || { format, quality: 23, bitrate: 2000 };
  }

  // 工具方法：获取推荐的音频提取参数
  static createAudioExtractParams(format: string): ExtractParams {
    const defaultParams: Record<string, ExtractParams> = {
      mp3: { audio_format: 'mp3', bitrate: 192 },
      wav: { audio_format: 'wav' },
      aac: { audio_format: 'aac', bitrate: 192 },
    };

    return defaultParams[format] || { audio_format: format };
  }
}
